package com.tianji.tools;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;

import cn.hutool.json.JSONUtil;
import com.tianji.api.client.trade.TradeClient;
import com.tianji.api.dto.trade.OrderConfirmVO;
import com.tianji.common.utils.UserContext;
import com.tianji.constants.Constant;
import com.tianji.tools.result.PrePlaceOrder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Slf4j
@Component
@RequiredArgsConstructor
public class OrderTools {

    private final TradeClient tradeClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Tool(description = Constant.Tools.PRE_PLACE_ORDER)
    public PrePlaceOrder prePlaceOrder(@ToolParam(description = Constant.ToolParams.COURSE_IDS) List<Number> ids,
                                       ToolContext toolContext) {
        // 注意要设置用户ID，用于身份验证，否则在Feign调用时会出现401错误
        String userId = (String)toolContext.getContext().get("userId");
        UserContext.setUser(Long.parseLong(userId));
        // 和课程信息卡片类似，chatService那边也不需要做特别处理,卡片也可以复用，根据传入data的不同展示不同的内容
        List<Long> list = ids.stream().map(Convert::toLong).toList();
        OrderConfirmVO orderConfirmVO = tradeClient.prePlaceOrder(list);
        PrePlaceOrder prePlaceOrder = PrePlaceOrder.of(orderConfirmVO);
        //下单成功返回之前，在Redis中设置requestId标记，表示该请求已经调用了Tools
        String requestId = (String) toolContext.getContext().get("requestId");
        stringRedisTemplate.opsForHash().put(Constant.PREFIX_OREDER,requestId, JSONUtil.toJsonStr(prePlaceOrder));
        log.info("Tools中 prePlaceOrder:{}", prePlaceOrder);
        return prePlaceOrder;
    }
}